# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
自定义的分页组件
"""


class Pagination(object):

    def __init__(self, request, queryset, form=None, page_size=10, plus=1, page_param="pageNum"):

        if request.method == "GET":
            page = request.GET.get(page_param, '1')     # 获取页码数，如果没有，默认第一页。
        elif request.method == "POST":
            page = request.POST.get(page_param, '1')
        else:
            page = 1
            print("没有设置这个请求方法, 给了初始值1")

        if page.isdecimal():
            page = int(page)
        else:
            page = 1

        self.total_count = queryset.count()
        self.page_size = page_size
        self.page = page
        self.plus = plus  # 计算出，显示当前页的前plus页，后plus页

        # 获取从start开始到end结束的page_size条数据
        self.start = (self.page - 1) * page_size
        self.end = self.page * page_size
        self.queryset = queryset[self.start:self.end]

        # 获取页面列表，通过列表形式在前端显示页码数
        self.total_page_count, div = divmod(self.total_count, self.page_size)
        if div:
            self.total_page_count += 1
        page_num_list = self.get_page_list()

        # 将内容封装到字典中，通过调用获取
        self.data = {
            "pageNumList": page_num_list,
            "pageNum": self.page,
            "total": self.total_count,
            "form": form,
            "rows": self.queryset
        }

    def get_page_list(self):

        page_num_list = []  # 存储页码
        center_page_num = self.page  # 显示页的中心数。当最前和最后页数据时，始终保持中位

        # 根据页码数量以及当前页码处理显示页码问题
        if self.total_page_count < (self.plus * 2 + 1):  # 判断是否小于最大页码显示数量
            for i in range(1, self.total_page_count + 1):
                page_num_list.append(i)
        else:
            if self.page <= self.plus:  # 当前页码小于 显示页码/2+1 时的处理
                center_page_num = self.plus + 1
            elif self.page > (self.total_page_count - self.plus):
                center_page_num = self.total_page_count - self.plus

            for i in range(center_page_num - self.plus, center_page_num + self.plus + 1):
                page_num_list.append(i)
        return page_num_list

    def get_content(self):
        return self.data
